<script setup>
import { computed, onMounted, ref, watch, h } from "vue";
import { CaretLeft, Back } from "@element-plus/icons-vue";
import ace from "brace";
import "brace/mode/python";
import "brace/theme/monokai";
import "brace/ext/language_tools";

import { getDevicePoints } from "@/api/device";
import { ElMessageBox } from "element-plus";

const props = defineProps({
  devices: {
    default: [],
    type: Array
  }
})

const text = defineModel()

const editorRef = ref()

let editor = null

onMounted(() => {
  editor = ace.edit(editorRef.value);
  editor.getSession().setMode('ace/mode/python');
  editor.setTheme("ace/theme/monokai");
  editor.setOptions({
    // 默认:false
    wrap: true, // 换行
    fontSize: "16px",
    autoScrollEditorIntoView: false, // 自动滚动编辑器视图
    enableLiveAutocompletion: true, // 智能补全
    enableBasicAutocompletion: true // 启用基本完成 不推荐使用
  })
  editor.setValue(text.value, 1)
  editor.session.on("change", () => text.value = editor.getValue())
})

watch(text, val => {
  if (editor && editor.getValue() !== val) {
    editor.setValue(val)
  }
})

function inputToEditor(value) {
  editor?.insert(value)
}

function inputVarToEditor() {
  inputToEditor(`device.point["${selectPoint.value[0]}:${selectPoint.value[1]}"].${selectAttr.value}`)
}

const btnFunc = [
  { text: "网关名称", input: "gateway.name" },
  { text: "网关编号", input: "device.id" },
  { text: "网关位置", input: "device.position" },
  { text: "设备编号", input: "device.no" },
  { text: "设备名称", input: "device.name" },
  { text: "设备断线", input: "device.outage" },
  { text: "实时时间", input: "now()" },
]

let devices = ref([])
watch(() => props.devices, val => {
  devices.value = []
  val.forEach(dev => {
    getDevicePoints(dev).then(res => {
      if (res.code === 200) {
        devices.value.push({
          no: dev,
          points: res.data
        })
      }
    })
  })
})

const cascaderProps = {
  expandTrigger: "hover",
}

const groupOptions = computed(() => {
  const pMap = {}
  devices.value.forEach(item => {
    item.points.forEach(p => {
      if (!pMap[p.group]) {
        pMap[p.group] = [p.name]
      } else {
        if (pMap[p.group].indexOf(p.name) === -1) {
          pMap[p.group].push(p.name)
        }
      }
    });
  })
  const res = []
  for (const group in pMap) {
    const item = {
      label: group,
      value: group,
      children: []
    }
    for (const point of pMap[group]) {
      item.children.push({
        label: point,
        value: point
      })
    }
    res.push(item)
  }
  return res
})

const selectPoint = ref()
const selectAttr = ref()

function handlePointClick(value) {
  let tips = []
  devices.value.forEach(dev => {
    let hasGroup = false
    let hasPoint = false
    let deviceNo = dev.no
    for (let i = 0; i < dev.points.length; i++) {
      const point = dev.points[i]
      deviceNo = point.deviceNo
      console.log("point: ", point);
      if (point.group === value[0]) {
        hasGroup = true
      }
      if (point.group === value[0] && point.name === value[1]) {
        hasPoint = true
        break
      }
    }
    if (!hasGroup) {
      tips.push(h("p", null, `${deviceNo} 不存在分组 ${value[0]}`))
    } else if (!hasPoint) {
      tips.push(h("p", null, `${deviceNo} 不存在点位 ${value[1]}`))
    }
  })
  if (tips.length > 0) {
    let s = tips.join()
    ElMessageBox.confirm(h("div", null, tips), "提示", {
      type: "warning",
      confirmButtonText: "确定",
      showCancelButton: false
    }).then(() => {})
  }
}
</script>

<template>
  <div ref="editorRef" class="editor-box"></div>
  <div class="quick-input">
    <el-row :gutter="8">
      <el-col class="title">快捷输入面板</el-col>
      <el-col v-for="f in btnFunc" :span="12" :lg="8" :xl="6">
        <el-button 
          style="width: 100%; margin-top: 12px;"
          text bg type="primary"
          :icon="CaretLeft" 
          @click="inputToEditor(f.input)"
        >{{ f.text }}</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="8" style="margin-top: 12px;">
      <el-col :span="8">
        <el-cascader 
          placeholder="选择点位" 
          v-model="selectPoint" 
          :props="cascaderProps" 
          :options="groupOptions" 
          @change="handlePointClick"
        />
      </el-col>
      <el-col :span="8">
        <el-select v-model="selectAttr" placeholder="选择属性">
          <el-option label="当前值" value="value" />
          <el-option label="上一次值" value="last" />
          <el-option label="描述信息" value="desc" />
          <el-option label="上次更新时间" value="updateAt" />
        </el-select>
      </el-col>
      <el-col :span="8">
        <el-button 
          style="width: 100%;" 
          bg text type="primary" 
          :icon="Back"
          @click="inputVarToEditor"
        >插入变量</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.editor-box {
  height: 480px;
  width: 60%;
}
.quick-input {
  height: 100%;
  width: 40%;
  box-sizing: border-box;
  padding: 24px;
  .title {
    width: 100%;
    text-align: center;
    font-size: 16px;
    font-weight: 700;
  }
}
</style>
